import * as app from '../../common/utils/BaseApp'
import { deepClone, getDictName } from '@/utils'
import * as ck from '../../common/utils/validater'
import { hasActionPriv } from '@/utils/perm'
import * as elg from '../../common/utils/ElmGenerator'

import { getRoleList, createRole, updateRole, deleteRole } from '@/api/system/role'
import langFile from './role.lang'
const base = app.install({ langObj: langFile })
const pageMode = {
  add: 'add',
  detailAdd: 'detailAdd',
  update: 'update'
}
export default {
  mixins: [base],
  data() {
    return {
      formObj: {
        searchForm: {
          // ----------------------- 角色查询条件 ---------------------
          role: {
            roleId: '',
            roleName: '',
            status: ''
          },
          likeSearch: {
            role: ['roleId', 'roleName']
          }
        },
        addForm: {
          // ----------------------- 角色Form结构 ---------------------
          role: {
            id: undefined,
            roleId: '',
            roleName: '',
            adminFlg: '0',
            sortOrder: '',
            status: '1',
            memo: ''
          },
          showFlg: {
            role: false
          },
          showMode: {
            role: ''
          }
        }
      },
      listObj: {
        // ----------------------- 角色列表 ---------------------
        role: {
          ...base.$gcom.getDefListObj(),
          selectedData: []
        }
      }
    }
  },
  computed: {
    isAddRole() {
      return this.formObj.addForm.showMode.role === pageMode.add ||
             this.formObj.addForm.showMode.role === pageMode.detailAdd
    },
    // ----------------------- 角色查询条件Layout ---------------------
    roleSearchFormLayout() {
      const formItems = [
        elg.createInput(this, { bindId: 'roleId', propsOpt: { width: 180 }}),
        elg.createInput(this, { bindId: 'roleName', propsOpt: { width: 180 }}),
        elg.createSelect(this, { bindId: 'status',
          optionList: elg.createChildOption(this.$dictObj['sys_valid_flg'].dict), propsOpt: { width: 160 }}),

        hasActionPriv(['sys:role:query']) === false ? null
          : elg.createButton(this, this.handleSearchRole, { langId: 'search', actionValid: true, propsOpt: { icon: 'el-icon-search' }}),
        elg.createBR(),
        hasActionPriv(['sys:role:add']) === false ? null
          : elg.createButton(this, this.handleAddRole, { langId: 'add', propsOpt: { icon: 'el-icon-edit' }})
      ]
      const rules = {
        roleId: [ck.createMaxLenValidater(this, 20)],
        roleName: [ck.createMaxLenValidater(this, 30)]
      }
      return { formItems: formItems, rules: rules }
    },
    // ----------------------- 角色新增/修改Form Layout ---------------------
    roleAddFormLayout() {
      const _target = this.formObj.addForm.role

      let adminFlgOpts = deepClone(this.$dictObj['sys_admin_flg'].dict)
      const isStatusDisabled = _target.adminFlg === '1'
      if (_target.adminFlg === '1') _target.status = '1'

      let isRoleIdDisabled = false
      if (this.isAddRole === false) {
        isRoleIdDisabled = true
        // 超级管理员只能追加一个
        adminFlgOpts = adminFlgOpts.map((item) => {
          item['disabled'] = _target.adminFlg !== item.id
          return item
        })
      }

      const formItems = [
        elg.createInput(this, { bindId: 'roleId', isDisabled: isRoleIdDisabled, propsOpt: { width: 180 }}),
        elg.createInput(this, { bindId: 'roleName', propsOpt: { width: 180 }}),
        elg.createInputNumber(this, { bindId: 'sortOrder' }),
        elg.createRadioButtonGroup(this, { bindId: 'adminFlg',
          optionList: elg.createChildRadioButton(adminFlgOpts) }),
        elg.createSelect(this, { bindId: 'status', isDisabled: isStatusDisabled,
          optionList: elg.createChildOption(this.$dictObj['sys_valid_flg'].dict), propsOpt: { width: 160 }}),
        elg.createTextArea(this, { bindId: 'memo' })
      ]
      const footerItems = [
        hasActionPriv(['sys:role:add', 'sys:role:update']) === false ? null
          : elg.createButton(this, this.handleSaveRole, { langId: 'confirm', actionValid: true, propsOpt: { icon: '' }})
      ]
      const rules = {
        roleId: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 20)
        ],
        roleName: [
          ck.createRequiredValidater(this), ck.createMaxLenValidater(this, 30)
        ],
        sortOrder: [
          ck.createRequiredValidater(this)
        ],
        status: [
          ck.createRequiredValidater(this)
        ],
        memo: [
          ck.createMaxLenValidater(this, 255)
        ]
      }
      return { formItems: formItems, footerItems: footerItems, rules: rules }
    },
    // ----------------------- 角色列表 Layout ---------------------
    roleListLayout() {
      const itemColumns = [
        elg.createTableColumn(this, { bindId: 'roleId', align: 'left' }),
        elg.createTableColumn(this, { bindId: 'roleName', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'status',
          formatter: {
            formatFnc: (row, v) => {
              return getDictName(this.$dictObj['sys_valid_flg'].dict, v)
            }
          }, align: 'center' }),
        elg.createTableColumn(this, { bindId: 'sortOrder', align: 'center' }),
        elg.createTableColumn(this, { bindId: 'memo', align: 'center' })
      ]
      const actionColumns = [
        hasActionPriv(['sys:role:update']) === false ? null
          : elg.createTableAction(this, { langId: 'edit', actionFnc: this.handleUpdateRole }),
        hasActionPriv(['sys:role:delete']) === false ? null
          : elg.createTableAction(this, { langId: 'delete', actionFnc: this.handleDeleteRole, visableFnc: (row, index) => {
            return (row.adminFlg !== '1')
          } })
      ]
      return { columns: itemColumns, actions: actionColumns }
    }
  },
  created() {
    this.$gcom.formObj = deepClone(this.formObj)
    this.searchRoleList()
  },
  methods: {
    // ----------------------- 角色列表查询 ---------------------
    async searchRoleList() {
      const _target = this.listObj.role
      try {
        _target.listLineLoading = true

        const result = await getRoleList({
          searchForm: this.formObj.searchForm.role,
          likeSearch: this.formObj.searchForm.likeSearch.role,
          pagingDefine: this.listObj.role.pagingDefine
        })

        _target.listLine = result.data.listLine
        _target.lineNum = result.data.lineNum
      } catch (err) {
        console.log(err)
      } finally {
        setTimeout(() => {
          _target.listLineLoading = false
        }, 0)
      }
    },
    handleSearchRole() {
      this.validateAll(['searchForm'], () => {
        this.listObj.role.pagingDefine.page = 1
        this.searchRoleList()
      })
    },
    async handleAddRole(row, index) {
      this.openDialog('role', pageMode.add)
    },
    async handleUpdateRole(row, index) {
      this.openDialog('role', pageMode.update, row)
    },
    // ----------------------- 角色信息保存 ---------------------
    handleSaveRole() {
      this.validateAll(['roleEditDlg'], async() => {
        const _form = { ... this.formObj.addForm.role }
        if (this.isAddRole) {
          await createRole(_form)
        } else {
          await updateRole(_form)
        }
        this.listObj.role.pagingDefine.page = 1
        this.searchRoleList()
        this.formObj.addForm.showFlg.role = false
      })
    },
    // ----------------------- 角色信息删除 ---------------------
    async handleDeleteRole(row, index) {
      this.$showConfirm({ msg: this.getLang('message.rule.deleteRoleConfirm'), ok: async() => {
        await deleteRole(row.id)
        setTimeout(async() => {
          this.listObj.role.pagingDefine.page = 1
          this.searchRoleList()
        }, 500)
      } })
    },
    // ----------------------- Open Dialog ---------------------
    openDialog(target, mode, row, index) {
      const data = row === undefined ? this.$gcom.formObj.addForm[target] : row
      this.formObj.addForm[target] = { ...data }
      this.formObj.addForm.showFlg[target] = true
      this.formObj.addForm.showMode[target] = mode
    }
  }
}
